﻿using Microsoft.AspNetCore.Http;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using XiAnAirport.DAL;
using XiAnAirport.ElevatorWebSocket;
using XiAnAirport.Models;

namespace XiAnAirport.BUS
{
    public class MaintainBUS
    {
        public ResponseMessage QueryMaintainHistoryList(MaintainInfo maintaininfo)
        {
            ResponseMessage message = new ResponseMessage();

            MaintainDAL da = new MaintainDAL();
            List<MaintainInfo> content = da.QueryMaintainHistoryList(maintaininfo);
            message.errcode = 0;
            message.errmsg = "";
            message.data = content;
            message.total = da.QueryMaintainHistoryCount(maintaininfo);

            return message;
        }

        public ResponseMessage LoadMaintain(int maintainid)
        {
            ResponseMessage message = new ResponseMessage();
            MaintainDAL da = new MaintainDAL();
            MaintainInfo content = da.LoadMaintain(maintainid);
            InspectionPlanDAL inspectionPlanDAL = new InspectionPlanDAL();
            if (content != null)
            {
                if (!string.IsNullOrEmpty(content.maintenanceDatetime))
                {
                    content.maintenanceDatetime = Convert.ToDateTime(content.maintenanceDatetime).ToString("yyyy-MM-dd HH:mm:ss");
                }
                if (!string.IsNullOrEmpty(content.receiveTime))
                {
                    content.receiveTime = Convert.ToDateTime(content.receiveTime).ToString("yyyy-MM-dd HH:mm:ss");
                }
                if (!string.IsNullOrEmpty(content.arriveTime))
                {
                    content.arriveTime = Convert.ToDateTime(content.arriveTime).ToString("yyyy-MM-dd HH:mm:ss");
                }
                if (!string.IsNullOrEmpty(content.completeTime))
                {
                    content.completeTime = Convert.ToDateTime(content.completeTime).ToString("yyyy-MM-dd HH:mm:ss");
                }

                message.errcode = 0;
                message.errmsg = "";
                message.data = content;
                message.total = 1;
            }
            else
            {
                message.errcode = 1;
                message.errmsg = "未查询到相关信息";
                message.data = null;
                message.total = 0;
            }

            return message;
        }

        public ResponseMessage QueryMaintainPlanInfo(MaintainInfo maintaininfo)
        {
            ResponseMessage message = new ResponseMessage();
            MaintainDAL da = new MaintainDAL();
            List<MaintainInfo> content = da.QueryMaintainPlanInfo(maintaininfo);
            message.errcode = 0;
            message.errmsg = "";
            message.data = content;
            message.total = da.QueryMaintainPlanCount(maintaininfo);

            return message;
        }

        public string UploadFileToServer(IFormFile file, string webRootPath)
        {
            string result = string.Empty;
            try
            {
                String Tpath = "/File/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
                string name = file.FileName;
                string FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                string FilePath = webRootPath + Tpath;

                string type = Path.GetExtension(name);
                DirectoryInfo di = new DirectoryInfo(FilePath);

                if (!di.Exists) { di.Create(); }

                using (FileStream fs = File.Create(FilePath + FileName + type))
                {
                    // 复制文件
                    file.CopyTo(fs);
                    fs.Flush();
                    fs.Close();
                }
                result = FilePath + FileName + type;

            }
            catch (Exception e)
            {
                result = "fail,文件导入失败" + e.ToString();
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "导入维保工单";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("导入维保工单" + e.ToString());
            }

            return result;
        }

        public string ImportTableToData(DataTable dt)
        {
            MaintainDAL da = new MaintainDAL();
            ResponseMessage message = new ResponseMessage();
            string addfailinfo = string.Empty;
            string failinfo = string.Empty;
            try
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string equipment = dt.Rows[i][0].ToString();
                    string elevatorname = dt.Rows[i][1].ToString();
                    string order = dt.Rows[i][2].ToString();
                    string groupno = dt.Rows[i][3].ToString();
                    string maintaintime = dt.Rows[i][5].ToString();
                    string properties = GetProperties(dt.Rows[i][12].ToString());

                    int Elevatorid = da.GetElevatorID(equipment);

                    if (Elevatorid == 0)
                    {
                        addfailinfo += (i + 2).ToString() + ",";
                        continue;
                    }

                    MaintainInfo maininfo = new MaintainInfo();
                    maininfo.elevatorID = Elevatorid;
                    maininfo.maintenanceGroupID = 0;
                    maininfo.maintenanceNo = order;
                    maininfo.maintenanceProperties = properties;
                    maininfo.maintenanceDatetime = maintaintime;

                    string result = da.AddMaintain(maininfo);
                    if (result != "success")
                    {
                        addfailinfo += (i + 2).ToString() + ",";
                    }
                }
                InitMaintime(0);
                InitWorkOrder();
                if (addfailinfo.Length > 0)
                {
                    failinfo += "第" + addfailinfo.Substring(0,addfailinfo.Length-1) + "行导入失败;";
                }
                if (failinfo.Length > 0)
                {
                    return failinfo;
                }
                else
                {
                    return "success";
                }
            }
            catch (Exception e)
            {
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "导入保养计划";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("导入保养计划" + e.ToString());
                return "导入保养计划失败," + e.ToString();
            }
        }

        public void InitMaintime(int id)
        {
            try
            {
                if (ElevatorStateBUS.device_list != null)
                {
                    ElevatorAreaDAL da = new ElevatorAreaDAL();
                    if (id > 0)
                    {
                        int dataid = ElevatorStateBUS.device_list.FindIndex(x => x.id == id);
                        if (dataid > -1)
                        {
                            Elevator elevator1 = ElevatorStateBUS.device_list[dataid];
                            elevator1.lastmaintenanceTime = da.QuerylastMaintenance(elevator1.id);
                            elevator1.maintenanceTime = da.QuerylastRepairTime(elevator1.id);
                            elevator1.nextmaintenanceTime = da.QueryNextMaintenance(elevator1.id);
                            ElevatorStateBUS.device_list[dataid] = elevator1;
                        }
                    }
                    else
                    {

                        for (int i = 0; i < ElevatorStateBUS.device_list.Count; i++)
                        {
                            Elevator elevator1 = ElevatorStateBUS.device_list[i];
                            elevator1.lastmaintenanceTime = da.QuerylastMaintenance(elevator1.id);
                            elevator1.maintenanceTime = da.QuerylastRepairTime(elevator1.id);
                            elevator1.nextmaintenanceTime = da.QueryNextMaintenance(elevator1.id);
                            ElevatorStateBUS.device_list[i] = elevator1;
                        }
                    }

                }
            }
            catch
            {

            }
        }

        public string GetProperties(string properties)
        {
            string result = string.Empty;
            switch (properties)
            {
                case "Q":
                    result = "季度保养";
                    break;
                case "N":
                    result = "半月保养";
                    break;
                case "T":
                    result = "半年保养";
                    break;
                case "U":
                    result = "年度保养";
                    break;
                case "I":
                    result = "年度自检";
                    break;
                case "K":
                    result = "政府自检";
                    break;
                case "NC1":
                    result = "半月门清洁";
                    break;
                case "NC2":
                    result = "半月总体清洁";
                    break;
                case "QC1":
                    result = "季度门清洁";
                    break;
                case "QC2":
                    result = "季度总体清洁";
                    break;
                case "TC1":
                    result = "半年门清洁";
                    break;
                case "TC2":
                    result = "半年总体清洁";
                    break;
                case "UC1":
                    result = "年度门清洁";
                    break;
                case "UC2":
                    result = "年度总体清洁";
                    break;
                default:
                    break;
            }
            return result;
        }

        public ResponseMessage DeleteMaintain(MaintainInfo maintaininfo)
        {
            ResponseMessage message = new ResponseMessage();
            MaintainDAL da = new MaintainDAL();
            string result = string.Empty;
            try
            {
                result = da.DeleteMaintain(maintaininfo);

                if (result.Contains("success"))
                {
                    InitMaintime(maintaininfo.elevatorID);
                    InitWorkOrder();
                    UpdateElevatorState(maintaininfo.elevatorID);
                    message.errcode = 0;
                    message.errmsg = "";
                    message.data = null;
                    message.total = 1;
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = result;
                    message.data = "删除保养计划失败";
                    message.total = 0;
                }
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = "删除保养计划异常";
                message.data = null;
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "删除保养计划";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("删除保养计划" + e.ToString());
            }

            return message;
        }

        public ResponseMessage GetStateList()
        {
            ResponseMessage message = new ResponseMessage();
            MaintainDAL da = new MaintainDAL();
            try
            {
                List<WorkorderState> content = da.GetStateList();

                message.errcode = 0;
                message.errmsg = "";
                message.data = content;
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = null;
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "查询保养工单状态";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("查询保养工单状态" + e.ToString());
            }
            return message;
        }

        public ResponseMessage AddMaintain(MaintainInfo maintaininfo)
        {
            ResponseMessage message = new ResponseMessage();
            MaintainDAL da = new MaintainDAL();
            string result = string.Empty;
            try
            {
                if (string.IsNullOrEmpty(maintaininfo.preparationTime))
                {
                    maintaininfo.preparationTime = "null";
                }
                else
                {
                    maintaininfo.preparationTime = string.Format("'{0}'", Convert.ToDateTime(maintaininfo.preparationTime).ToString("yyyy-MM-dd HH:mm:ss"));
                }
                if (string.IsNullOrEmpty(maintaininfo.receiveTime))
                {
                    maintaininfo.receiveTime = "null";
                }
                else
                {
                    maintaininfo.receiveTime = string.Format("'{0}'", Convert.ToDateTime(maintaininfo.receiveTime).ToString("yyyy-MM-dd HH:mm:ss"));
                }
                if (string.IsNullOrEmpty(maintaininfo.arriveTime))
                {
                    maintaininfo.arriveTime = "null";
                }
                else
                {
                    maintaininfo.arriveTime = string.Format("'{0}'", Convert.ToDateTime(maintaininfo.arriveTime).ToString("yyyy-MM-dd HH:mm:ss"));
                }
                if (string.IsNullOrEmpty(maintaininfo.completeTime))
                {
                    maintaininfo.completeTime = "null";
                }
                else
                {
                    maintaininfo.completeTime = string.Format("'{0}'", Convert.ToDateTime(maintaininfo.completeTime).ToString("yyyy-MM-dd HH:mm:ss"));
                }
                if (string.IsNullOrEmpty(maintaininfo.acceptanceTime))
                {
                    maintaininfo.acceptanceTime = "null";
                }
                else
                {
                    maintaininfo.acceptanceTime = string.Format("'{0}'", Convert.ToDateTime(maintaininfo.acceptanceTime).ToString("yyyy-MM-dd HH:mm:ss"));
                }

                if (string.IsNullOrEmpty(maintaininfo.maintenanceDatetime))
                {
                    maintaininfo.maintenanceDatetime = "null";
                }
                else
                {
                    maintaininfo.maintenanceDatetime = string.Format("'{0}'", Convert.ToDateTime(maintaininfo.maintenanceDatetime).ToString("yyyy-MM-dd HH:mm:ss"));
                }

                //maintaininfo.maintenanceNo = GetWorkNo();
                result = da.InsertMaintain(maintaininfo);

                if (result.Contains("success"))
                {
                    InitMaintime(maintaininfo.elevatorID);
                    InitWorkOrder();
                    UpdateElevatorState(maintaininfo.elevatorID);
                    message.errcode = 0;
                    message.errmsg = "";
                    message.data = null;
                    message.total = 1;
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = "新增保养计划失败";
                    message.data = null;
                    message.total = 0;
                }
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = "新增保养计划异常";
                message.data = null;
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "新增保养计划";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("新增保养计划" + e.ToString());
            }

            return message;
        }

        public ResponseMessage UpdateMaintain(MaintainInfo maintaininfo)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                if (string.IsNullOrEmpty(maintaininfo.preparationTime))
                {
                    maintaininfo.preparationTime = "null";
                }
                else
                {
                    maintaininfo.preparationTime = string.Format("'{0}'", Convert.ToDateTime(maintaininfo.preparationTime).ToString("yyyy-MM-dd HH:mm:ss"));
                }
                if (string.IsNullOrEmpty(maintaininfo.receiveTime))
                {
                    maintaininfo.receiveTime = "null";
                }
                else
                {
                    maintaininfo.receiveTime = string.Format("'{0}'", Convert.ToDateTime(maintaininfo.receiveTime).ToString("yyyy-MM-dd HH:mm:ss"));
                }
                if (string.IsNullOrEmpty(maintaininfo.arriveTime))
                {
                    maintaininfo.arriveTime = "null";
                }
                else
                {
                    maintaininfo.arriveTime = string.Format("'{0}'", Convert.ToDateTime(maintaininfo.arriveTime).ToString("yyyy-MM-dd HH:mm:ss"));
                }
                if (string.IsNullOrEmpty(maintaininfo.completeTime))
                {
                    maintaininfo.completeTime = "null";
                }
                else
                {
                    maintaininfo.completeTime = string.Format("'{0}'", Convert.ToDateTime(maintaininfo.completeTime).ToString("yyyy-MM-dd HH:mm:ss"));
                }
                if (string.IsNullOrEmpty(maintaininfo.acceptanceTime))
                {
                    maintaininfo.acceptanceTime = "null";
                }
                else
                {
                    maintaininfo.acceptanceTime = string.Format("'{0}'", Convert.ToDateTime(maintaininfo.acceptanceTime).ToString("yyyy-MM-dd HH:mm:ss"));
                }

                if (string.IsNullOrEmpty(maintaininfo.maintenanceDatetime))
                {
                    maintaininfo.maintenanceDatetime = "null";
                }
                else
                {
                    maintaininfo.maintenanceDatetime = string.Format("'{0}'", Convert.ToDateTime(maintaininfo.maintenanceDatetime).ToString("yyyy-MM-dd HH:mm:ss"));
                }

                MaintainDAL da = new MaintainDAL();
                string result = string.Empty;
                result = da.UpdateMaintain(maintaininfo);
                if (result == "success")
                {
                    InitMaintime(maintaininfo.elevatorID);
                    InitWorkOrder();
                    UpdateElevatorState(maintaininfo.elevatorID);

                    message.errcode = 0;
                    message.errmsg = "";
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = "修改保养工单失败";
                }
            }
            catch (Exception ex)
            {
                message.errcode = 1;
                message.errmsg = "修改保养工单异常";
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "修改保养计划";
                errorLogInfo.errorMsg = ex.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("修改保养计划" + ex.ToString());
            }
            return message;
        }

        public string GetWorkNo()
        {
            while (true)
            {
                Random rd = new Random();
                int num = rd.Next(1, 9999);
                string orderNO = DateTime.Now.ToString("yyMMdd") + num.ToString().PadLeft(4, '0');
                if (CheckWorkNo(orderNO))
                {
                    return orderNO;
                }
            }
        }

        public bool CheckWorkNo(string orderNO)
        {
            MaintainDAL maintainDAL = new MaintainDAL();
            try
            {
                string number = maintainDAL.CheckWorkNo(orderNO);
                if (string.IsNullOrEmpty(number))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }

        public ResponseMessage QueryAnnualMaintainHistoryList(MaintainInfo maintaininfo)
        {
            ResponseMessage message = new ResponseMessage();

            MaintainDAL da = new MaintainDAL();
            List<MaintainInfo> content = da.QueryAnnualMaintainHistoryList(maintaininfo);

            message.errcode = 0;
            message.errmsg = "";
            message.data = content;
            message.total = da.QueryAnnualMaintainHistoryCount(maintaininfo);
            return message;
        }

        public ResponseMessage ExportMaintain(MaintainInfo maintainInfo, string path)
        {
            ResponseMessage response = new ResponseMessage();
            try
            {
                MaintainDAL maintainDAL = new MaintainDAL();
                List<MaintainInfo> list = maintainDAL.QueryMaintainPlanInfo(maintainInfo);
                if (list.Count < 65536)
                {
                    string sFileName = "保养工单.xlsx";

                    FileInfo file = new FileInfo(Path.Combine(path, sFileName));

                    file.Delete();
                    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                    using (ExcelPackage package = new ExcelPackage(file))

                    {
                        // 添加worksheet

                        ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("保养工单");

                        //添加头
                        worksheet.Cells[1, 1].Value = "工单编号";
                        worksheet.Cells[1, 2].Value = "电梯名称";
                        worksheet.Cells[1, 3].Value = "设备位置";
                        worksheet.Cells[1, 4].Value = "例行保养日期";
                        worksheet.Cells[1, 5].Value = "保养性质";
                        worksheet.Cells[1, 6].Value = "保养结果";
                        worksheet.Cells[1, 7].Value = "工单状态";

                        //添加值

                        for (int i = 0; i < list.Count; i++)
                        {
                            MaintainInfo maintain = list[i];
                            worksheet.Cells[i + 2, 1].Value = maintain.maintenanceNo;
                            worksheet.Cells[i + 2, 2].Value = maintain.elevatorName;
                            worksheet.Cells[i + 2, 3].Value = maintain.mainAreaName + "-" + maintain.areaName;
                            worksheet.Cells[i + 2, 4].Value = Convert.ToDateTime(maintain.maintenanceDatetime).ToString("yyyy/MM/dd HH:mm:ss");
                            worksheet.Cells[i + 2, 5].Value = maintain.maintenanceProperties;
                            worksheet.Cells[i + 2, 6].Value = maintain.maintenanceResult;
                            worksheet.Cells[i + 2, 7].Value = maintain.workorderStateName;
                        }
                        package.Save();

                    }
                    response.errcode = 0;
                    response.errmsg = "";
                    response.data = "/" + sFileName;
                }
                else
                {
                    response.errcode = 1;
                    response.errmsg = "数据量超过65535条，无法导出";
                }

            }
            catch (Exception ex)
            {
                response.errcode = 1;
                response.errmsg = "导出失败";
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "导出保养工单";
                errorLogInfo.errorMsg = ex.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("导出保养工单" + ex.ToString());
            }
            return response;
        }

        public ResponseMessage GenerateMaintainNo()
        {
            ResponseMessage message = new ResponseMessage();
            string workorder = GetWorkNo();
            message.data = workorder;
            return message;
        }

        public ResponseMessage ExportMaintainHistory(MaintainInfo maintainInfo, string path)
        {
            ResponseMessage response = new ResponseMessage();
            try
            {
                MaintainDAL maintainDAL = new MaintainDAL();
                List<MaintainInfo> list = new List<MaintainInfo>();
                if (string.IsNullOrEmpty(maintainInfo.ids))
                {
                    if (maintainInfo.type == 0)//工单
                    {
                        list = maintainDAL.QueryMaintainPlanInfo(maintainInfo);
                    }
                    else//历史记录
                    {
                        list = maintainDAL.QueryMaintainHistoryList(maintainInfo);
                    }
                }
                else
                {
                    list = maintainDAL.QueryMaintainHistoryByIds(maintainInfo);
                }

                if (list.Count < 65536)
                {
                    string sFileName = "保养工单.xlsx";

                    FileInfo file = new FileInfo(Path.Combine(path, sFileName));

                    file.Delete();
                    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                    using (ExcelPackage package = new ExcelPackage(file))

                    {
                        // 添加worksheet

                        ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("保养工单");

                        //添加头
                        worksheet.Cells[1, 1].Value = "工单编号";
                        worksheet.Cells[1, 2].Value = "设备名称";
                        worksheet.Cells[1, 3].Value = "设备编号";
                        worksheet.Cells[1, 4].Value = "设备位置";
                        worksheet.Cells[1, 5].Value = "工单状态";
                        worksheet.Cells[1, 6].Value = "保养性质";
                        worksheet.Cells[1, 7].Value = "维保员";
                        worksheet.Cells[1, 8].Value = "维保员工号";
                        worksheet.Cells[1, 9].Value = "维保员电话";
                        worksheet.Cells[1, 10].Value = "保养时间";
                        worksheet.Cells[1, 11].Value = "保养结果";
                        worksheet.Cells[1, 12].Value = "制单时间";
                        worksheet.Cells[1, 13].Value = "接收时间";
                        worksheet.Cells[1, 14].Value = "到达时间";
                        worksheet.Cells[1, 15].Value = "完成时间";
                        worksheet.Cells[1, 16].Value = "验收时间";
                        //添加值

                        for (int i = 0; i < list.Count; i++)
                        {
                            MaintainInfo maintain = list[i];
                            worksheet.Cells[i + 2, 1].Value = maintain.maintenanceNo;
                            worksheet.Cells[i + 2, 2].Value = maintain.elevatorName;
                            worksheet.Cells[i + 2, 3].Value = maintain.elevatorNo;
                            worksheet.Cells[i + 2, 4].Value = maintain.mainAreaName + "-" + maintain.areaName;
                            worksheet.Cells[i + 2, 5].Value = maintain.workorderStateName;
                            worksheet.Cells[i + 2, 6].Value = maintain.maintenanceProperties;
                            worksheet.Cells[i + 2, 7].Value = maintain.receiver;
                            worksheet.Cells[i + 2, 8].Value = maintain.receiverNo;
                            worksheet.Cells[i + 2, 9].Value = maintain.receiverPhone;
                            worksheet.Cells[i + 2, 10].Value = maintain.maintenanceDatetime == null ? "" : Convert.ToDateTime(maintain.maintenanceDatetime).ToString("yyyy/MM/dd HH:mm:ss");
                            worksheet.Cells[i + 2, 11].Value = maintain.maintenanceResult;
                            worksheet.Cells[i + 2, 12].Value = maintain.preparationTime == null ? "" : Convert.ToDateTime(maintain.preparationTime).ToString("yyyy/MM/dd HH:mm:ss");
                            worksheet.Cells[i + 2, 13].Value = maintain.receiveTime == null ? "" : Convert.ToDateTime(maintain.receiveTime).ToString("yyyy/MM/dd HH:mm:ss");
                            worksheet.Cells[i + 2, 14].Value = maintain.arriveTime == null ? "" : Convert.ToDateTime(maintain.arriveTime).ToString("yyyy/MM/dd HH:mm:ss");
                            worksheet.Cells[i + 2, 15].Value = maintain.completeTime == null ? "" : Convert.ToDateTime(maintain.completeTime).ToString("yyyy/MM/dd HH:mm:ss");
                            worksheet.Cells[i + 2, 16].Value = maintain.acceptanceTime == null ? "" : Convert.ToDateTime(maintain.acceptanceTime).ToString("yyyy/MM/dd HH:mm:ss");
                        }
                        package.Save();

                    }
                    response.errcode = 0;
                    response.errmsg = "";
                    response.data = "/" + sFileName;
                }
                else
                {
                    response.errcode = 1;
                    response.errmsg = "数据量超过65535条，无法导出";
                }

            }
            catch (Exception ex)
            {
                response.errcode = 1;
                response.errmsg = "导出失败";
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "导出保养历史";
                errorLogInfo.errorMsg = ex.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("导出保养历史" + ex.ToString());
            }
            return response;
        }

        public ResponseMessage ExportAnnualMaintainHistory(MaintainInfo maintainInfo, string path)
        {
            ResponseMessage response = new ResponseMessage();
            try
            {
                MaintainDAL maintainDAL = new MaintainDAL();
                List<MaintainInfo> list = maintainDAL.QueryAnnualMaintainHistoryList(maintainInfo);
                if (list.Count < 65536)
                {
                    string sFileName = "年检历史.xlsx";

                    FileInfo file = new FileInfo(Path.Combine(path, sFileName));

                    file.Delete();
                    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                    using (ExcelPackage package = new ExcelPackage(file))

                    {
                        // 添加worksheet

                        ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("年检历史");

                        //添加头
                        worksheet.Cells[1, 1].Value = "年检时间";
                        worksheet.Cells[1, 2].Value = "电梯名称";
                        worksheet.Cells[1, 3].Value = "年检员";
                        worksheet.Cells[1, 4].Value = "保养性质";
                        worksheet.Cells[1, 5].Value = "工单状态";

                        //添加值

                        for (int i = 0; i < list.Count; i++)
                        {
                            MaintainInfo maintain = list[i];
                            worksheet.Cells[i + 2, 1].Value = Convert.ToDateTime(maintain.maintenanceDatetime).ToString("yyyy/MM/dd HH:mm:ss");
                            worksheet.Cells[i + 2, 2].Value = maintain.elevatorName;
                            worksheet.Cells[i + 2, 3].Value = maintain.receiver;
                            worksheet.Cells[i + 2, 4].Value = maintain.maintenanceProperties;
                            worksheet.Cells[i + 2, 5].Value = maintain.workorderStateName;
                        }
                        package.Save();

                    }
                    response.errcode = 0;
                    response.errmsg = "";
                    response.data = "/" + sFileName;
                }
                else
                {
                    response.errcode = 1;
                    response.errmsg = "数据量超过65535条，无法导出";
                }

            }
            catch (Exception ex)
            {
                response.errcode = 1;
                response.errmsg = "导出失败";
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "导出年度保养工单";
                errorLogInfo.errorMsg = ex.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("导出年度保养工单" + ex.ToString());
            }
            return response;
        }

        public ResponseMessage BatchDeleteMaintain(string ids)
        {
            ResponseMessage message = new ResponseMessage();
            MaintainDAL da = new MaintainDAL();
            string result = string.Empty;
            try
            {
                result = da.BatchDeleteMaintain(ids);

                if (result.Contains("success"))
                {
                    InitWorkOrder();
                    message.errcode = 0;
                    message.errmsg = "";
                    message.data = null;
                    message.total = 1;
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = result;
                    message.data = "批量删除保养计划失败";
                    message.total = 0;
                }
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = "批量删除保养计划异常";
                message.data = null;
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "批量删除保养计划";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("批量删除保养计划" + e.ToString());
            }

            return message;
        }

        public static void InitWorkOrder()
        {
            try
            {
                MqttDataDAL mqttDataDAL = new MqttDataDAL();
                int maintenance = 0;

                for (int i = 0; i < 2; i++)
                {
                    try
                    {
                        string type = string.Empty;
                        int datanum = 0;

                        mqttdata mqttdata = new mqttdata();

                        if (i == 0)
                        {
                            type = "maintenanceTotal";
                            List<mqttdata> list = mqttDataDAL.QueryMqttdata("OrderIncomplete", "04", "KONE");
                            int old_value = (int)list.FirstOrDefault(x => x.dataType == "maintain").dataNum;
                            datanum = old_value + mqttDataDAL.QueryMaintainOrder();
                            maintenance = datanum;
                        }
                        else if (i == 1)
                        {
                            type = "maintenanceCompleted";
                            datanum = maintenance - mqttDataDAL.QueryInCompleteMaintainOrder();
                        }

                        mqttdata.dataNum = datanum;
                        mqttdata.manufacturer = "KONE";
                        mqttdata.manufacturerId = "04";
                        mqttdata.topicType = "TodayProcess";
                        mqttdata.dataType = type;
                        bool result = mqttDataDAL.CheckData(mqttdata.manufacturer, mqttdata.manufacturerId, type, mqttdata.topicType);

                        if (result)
                        {
                            mqttDataDAL.UpdateMqttData(mqttdata);
                        }
                        else
                        {
                            mqttDataDAL.AddMqttData(mqttdata);
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }
                bool result_5 = PushNoticeMessage("Refresh").Result;
                bool result_6 = PushKoneHomeMessage("RefreshHomePage").Result;
                bool result_7 = PushPromptMessage("RefreshPrompt").Result;
            }
            catch (Exception e)
            {
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "初始化工单数量";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("初始化工单数量" + e.ToString());
            }
        }

        public static async Task<bool> PushNoticeMessage(string message)
        {
            return await ElevatorWebSocketMiddleware.webSocketManage.PushNoticeMessage(message);
        }

        public static async Task<bool> PushKoneHomeMessage(string message)
        {
            return await ElevatorWebSocketMiddleware.webSocketManage.PushKoneHomeMessage(message);
        }

        public static async Task<bool> PushPromptMessage(string message)
        {
            return await ElevatorWebSocketMiddleware.webSocketManage.PushPromptMessage(message);
        }

        public void UpdateElevatorState(int elevatorid)
        {
            try
            {
                List<LiftStateALL> list = ElevatorStateBUS.state_list;
                ElevatorAreaDAL elevatorAreaDAL = new ElevatorAreaDAL();
                Elevator elevator = elevatorAreaDAL.LoadElevator(elevatorid);
                int ele_index = list.FindIndex(x => x.opcNO == elevator.opcNO);
                if (ele_index > -1)
                {
                    LiftStateALL liftStateALL = new LiftStateALL();
                    liftStateALL = list[ele_index];
                    liftStateALL.lastmaintenanceTime = elevatorAreaDAL.QuerylastMaintenance(elevator.id);
                    liftStateALL.maintenanceTime = elevatorAreaDAL.QuerylastRepairTime(elevator.id);
                    liftStateALL.nextmaintenanceTime = elevatorAreaDAL.QueryNextMaintenance(elevator.id);
                    ElevatorStateBUS bus = new ElevatorStateBUS();
                    bus.UpdateData(elevator.opcNO, liftStateALL);
                    //ElevatorStateBUS.UpdateData(elevator.opcNO, liftStateALL);
                    bool result = PushSingleElevatorMessage(elevator.id, liftStateALL).Result;
                }
            }
            catch (Exception e)
            {
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "修改单台电梯状态";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("修改单台电梯状态" + e.ToString());
            }
        }

        public async Task<bool> PushSingleElevatorMessage(int elevatorid, LiftStateALL liftStateALL)
        {
            return await ElevatorWebSocketMiddleware.webSocketManage.PushElevatorMessage(elevatorid, liftStateALL);
        }
    }
}
